import InterviewController from '@/services/interview';
import { IInterview } from '@/types/interview';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'umi';

// 请求方法
import { ITypeState } from '@/models/typeModel';

const InterviewDetail: React.FC = () => {
  const { interviewId } = useParams(); // 获取可能传递过来的 id
  const [interviewInfo, setInterviewInfo] = useState<IInterview>();
  const [typeName, setTypeName] = useState<string>();
  const dispatch = useDispatch(); // 获取 dispatch

  // 从仓库获取类型列表
  const { typeList }: ITypeState = useSelector((state: any) => state.type);

  useEffect(() => {
    // 如果类型列表为空，则初始化一次
    if (!typeList.length) {
      dispatch({
        type: 'type/_initTypeList',
      });
    }

    // 根据传递过来的 id 获取面试题详情
    async function fetchData() {
      // 根据问答 id 获取该问答具体的信息
      if (!interviewId) return;
      const { data } = await InterviewController.getInterviewById(interviewId);
      setInterviewInfo(data);
      // 获取 typeId 对应的 typeName
      const type = typeList.find((item) => item._id === data.typeId);
      setTypeName(type?.typeName);
    }
    fetchData();
  }, []);

  return (
    <PageContainer>
      <Card
        title={interviewInfo?.interviewTitle}
        style={{
          marginBottom: 10,
        }}
        extra={
          <Tag color="purple" key={interviewInfo?.typeId}>
            {typeName}
          </Tag>
        }
      >
        <div
          dangerouslySetInnerHTML={{
            __html: interviewInfo?.interviewContent
              ? interviewInfo?.interviewContent
              : '',
          }}
        ></div>
      </Card>
    </PageContainer>
  );
};

export default InterviewDetail;
